cmake_minimum_required(VERSION 3.19)
project(VideoPlayer LANGUAGES CXX)

# 设置C++标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

# 查找Qt6
find_package(Qt6 6.5 REQUIRED COMPONENTS Core Widgets)

# 设置Qt自动处理
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)

# 定义FFmpeg路径
set(FFMPEG_DIR "${CMAKE_CURRENT_SOURCE_DIR}/libs/ffmpeg")

# 检查FFmpeg根目录是否存在
if(NOT EXISTS "${FFMPEG_DIR}")
    message(FATAL_ERROR "FFmpeg目录不存在：${FFMPEG_DIR}")
endif()

# FFmpeg头文件和库配置
include_directories("${FFMPEG_DIR}/include")
link_directories("${FFMPEG_DIR}/bin")  # MSVC的.lib文件在bin目录
set(FFMPEG_LIBS avformat avcodec avutil swscale swresample avfilter)

# 定义SDL2路径
set(SDL2_DIR "${CMAKE_CURRENT_SOURCE_DIR}/libs/SDL2")

# 检查SDL2根目录是否存在
if(NOT EXISTS "${SDL2_DIR}")
    message(FATAL_ERROR "SDL2目录不存在：${SDL2_DIR}")
endif()

# SDL2头文件配置
include_directories("${SDL2_DIR}/include")

# 根据架构选择对应的SDL2库目录
if(CMAKE_SIZEOF_VOID_P EQUAL 8)
    set(SDL2_LIB_DIR "${SDL2_DIR}/lib/x64")      # 64位 LIB路径
    set(SDL2_BIN_DIR "${SDL2_DIR}/bin/win64")    # 64位 DLL路径
    message(STATUS "使用SDL2 64位库：${SDL2_LIB_DIR}")
else()
    set(SDL2_LIB_DIR "${SDL2_DIR}/lib/x86")      # 32位 LIB路径
    set(SDL2_BIN_DIR "${SDL2_DIR}/bin/win32")    # 32位 DLL路径
    message(STATUS "使用SDL2 32位库：${SDL2_LIB_DIR}")
endif()

# SDL2库配置
link_directories("${SDL2_LIB_DIR}")
set(SDL2_LIBS SDL2)  # Qt程序不需要SDL2main，它会重定义main函数

# 先创建目标
qt_add_executable(VideoPlayer
    WIN32 MACOSX_BUNDLE
    src/main.cpp
    src/ui/MainWindow.cpp
    src/ui/MainWindow.h
    src/ui/MainWindow.ui
    src/ui/VideoWidget.cpp
    src/ui/VideoWidget.h
    src/data/VideoFrame.cpp
    src/data/VideoFrame.h
    src/data/AudioFrame.cpp
    src/data/AudioFrame.h
    src/player/VideoDecoder.cpp
    src/player/VideoDecoder.h
    src/player/AudioDecoder.cpp
    src/player/AudioDecoder.h
    src/player/AudioOutput.cpp
    src/player/AudioOutput.h
    src/player/DecodeThread.cpp
    src/player/DecodeThread.h
)

# 修正：复制FFmpeg动态库（解决通配符问题）
file(GLOB FFMPEG_DLLS "${FFMPEG_DIR}/bin/*.dll")  # 获取所有.dll文件
if(FFMPEG_DLLS)
    add_custom_command(
        TARGET VideoPlayer
        POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different ${FFMPEG_DLLS} "$<TARGET_FILE_DIR:VideoPlayer>"
        COMMENT "复制FFmpeg动态库：${FFMPEG_DLLS}"
    )
else()
    message(FATAL_ERROR "未找到FFmpeg的.dll文件，请检查路径：${FFMPEG_DIR}/bin/*.dll")
endif()

# 复制SDL2动态库
file(GLOB SDL2_DLLS "${SDL2_BIN_DIR}/*.dll")  # 获取对应架构的.dll文件
if(SDL2_DLLS)
    add_custom_command(
        TARGET VideoPlayer
        POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different ${SDL2_DLLS} "$<TARGET_FILE_DIR:VideoPlayer>"
        COMMENT "复制SDL2动态库：${SDL2_DLLS}"
    )
else()
    message(FATAL_ERROR "未找到SDL2的.dll文件，请检查路径：${SDL2_BIN_DIR}/*.dll")
endif()

# 链接库
target_link_libraries(VideoPlayer
    PRIVATE
        Qt::Core
        Qt::Widgets
        ${FFMPEG_LIBS}
        ${SDL2_LIBS}
)
